package com.jokerpan.project.controller;

import com.jokerpan.project.annotation.AccessLimit;
import com.jokerpan.project.commons.ActionResult;
import com.jokerpan.project.commons.ListResult;
import com.jokerpan.project.commons.ResultBuilder;
import com.jokerpan.project.entity.Comment;
import com.jokerpan.project.service.CommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("comment")
@Api("评论表操作Api")
@PreAuthorize("hasPermission('','user:list')")
public class CommentController {

    @Resource
    CommentService commentService;

    @GetMapping("/queryList")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("查询所有评论分页")
    public ListResult<Object> queryList(Comment comment) {
        return ResultBuilder.buildListSuccess(this.commentService.queryList(comment));
    }

    @GetMapping("/queryByBlogId")
    @AccessLimit(seconds = 6, maxCount = 5)
    @ApiOperation("根据博客id查询所有评论")
    public ListResult<Object> queryByBlogId(Comment comment) {
        return ResultBuilder.buildListSuccess(this.commentService.queryByBlogId(comment));
    }

    @PostMapping("/add")
    @ApiOperation("新增评论")
    @AccessLimit(seconds = 6, maxCount = 5)
    @PreAuthorize("hasPermission('','user:add')")
    public ActionResult add(@RequestBody Comment comment) throws Exception {
        if (this.commentService.add(comment)){
            return ResultBuilder.buildActionSuccess();
        }else {
            return ResultBuilder.buildActionFailed();
        }
    }

    @PostMapping("/update")
    @ApiOperation("修改评论")
    @AccessLimit(seconds = 6, maxCount = 5)
    @PreAuthorize("hasRole('ROLE_USER')")
    public ActionResult update(@RequestBody Comment comment){
        return this.commentService.update(comment);
    }

    @PostMapping("/action")
    @ApiOperation("评论操作（点赞/踩）")
    @AccessLimit(seconds = 6, maxCount = 5)
    @PreAuthorize("hasPermission('','user:update')")
    public ActionResult likeAction(@RequestBody Comment comment){
        String action = comment.getAction();
        if (action.equals("like")){
            return this.commentService.like(comment);
        }else if (action.equals("dislike")){
            return this.commentService.dislike(comment);
        }else {
            return ResultBuilder.buildActionFailed("操作失败!");
        }
    }

    @GetMapping("/delete")
    @ApiOperation("删除评论")
    @AccessLimit(seconds = 6, maxCount = 5)
    @PreAuthorize("hasPermission('','user:update')")
    public ActionResult delete(@RequestParam("id") Integer id){
        return this.commentService.deleteById(id);
    }

}
